const { query } = require('../../../lib/db');
const { generateToken, comparePassword } = require('../../../lib/auth');
const { validate, loginSchema } = require('../../../lib/validation');

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({
      success: false,
      message: '方法不允许'
    });
  }

  try {
    // 验证请求数据
    const validation = validate(loginSchema, req.body);
    if (!validation.isValid) {
      return res.status(400).json({
        success: false,
        message: '请求数据验证失败',
        errors: validation.errors
      });
    }

    const { username, password } = validation.data;

    // 查询用户
    const users = await query('SELECT * FROM users WHERE username = ? AND status = 1', [username]);
    const user = users[0];

    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 验证密码
    const isValidPassword = await comparePassword(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 更新最后登录时间
    await query('UPDATE users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ?', [user.id]);

    // 生成 JWT Token
    const tokenPayload = {
      id: user.id,
      username: user.username,
      name: user.name,
      role: user.role,
      tenant_id: user.tenant_id
    };

    const token = generateToken(tokenPayload);

    // 返回用户信息（不包含密码）
    const userData = {
      id: user.id,
      username: user.username,
      name: user.name,
      employee_id: user.employee_id,
      department: user.department,
      tenant_id: user.tenant_id,
      email: user.email,
      phone: user.phone,
      role: user.role,
      last_login_at: user.last_login_at
    };

    res.status(200).json({
      success: true,
      message: '登录成功',
      data: {
        user: userData,
        token
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}